
package com.zlp.spring.mybatis.spring;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.Proxy;

/**
 * BeanFactory that enables injection of MyBatis mapper interfaces. It can be set up with a SqlSessionFactory or a
 * pre-configured SqlSessionTemplate.
 * <p>
 * Sample configuration:
 *
 * <pre class="code">
 * {@code
 *   <bean id="baseMapper" class="org.mybatis.spring.mapper.MapperFactoryBean" abstract="true" lazy-init="true">
 *     <property name="sqlSessionFactory" ref="sqlSessionFactory" />
 *   </bean>
 *
 *   <bean id="oneMapper" parent="baseMapper">
 *     <property name="mapperInterface" value="my.package.MyMapperInterface" />
 *   </bean>
 *
 *   <bean id="anotherMapper" parent="baseMapper">
 *     <property name="mapperInterface" value="my.package.MyAnotherMapperInterface" />
 *   </bean>
 * }
 * </pre>
 * <p>
 * Note that this factory can only inject <em>interfaces</em>, not concrete classes.
 *
 * @author Eduardo Macarron
 *
 * @see SqlSessionTemplate
 */
public class MyMapperFactoryBean implements FactoryBean {

  private Class mapperInterface;


  public MyMapperFactoryBean() {
    // intentionally empty
    System.out.println("intentionally empty");
  }

  public MyMapperFactoryBean(Class mapperInterface) {
    this.mapperInterface = mapperInterface;
  }



  /**
   * {@inheritDoc}
   */
  @Override
  public Object getObject() throws Exception {

    Object object = Proxy.newProxyInstance(mapperInterface.getClassLoader(),
            new Class[] { mapperInterface }, new MyInvocationHandler());
    return object;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Class<?> getObjectType() {
    return this.mapperInterface;
  }


}
